#ifndef SYNCMANAGER_H
#define SYNCMANAGER_H

#include <QtGui>
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>

#include "neophonebookentry.h"

class SyncManager : public QWidget
{
    Q_OBJECT
    public:
		static const int MESSAGE_SIZE = 1024;
		QString SYNC;
		QString ACTION;
		QString COMPLETE;
		QString FINISH;
		QString ACTION_SYNC;
		QString ACTION_ADD;
		QString ACTION_DELETE;
		QString ACTION_REPLACE;
		QString ACTION_CALL;
		QString ACTION_STOP_CALL;
		enum Status {LISTEN, STOP, CONNECT, CONNECTING, DISCONNECT,SYNCING, SYNCED,
				ERROR_ADDRESS, ERROR_NETWORK};
		enum Servlet {DISPATCHER, FILE_UPLOAD};
        SyncManager();
        ~SyncManager();
	void setHomeDir(QString homeDir);
		static bool validateIp(QString ipStr);
		static bool validatePort(QString portStr);

	signals:
		//===== Network =====
		void statusSignal(int status);

		//===== Phone Book =====
		void addContactSignal(NeoPhoneBookEntry *entry);
		void replaceContactSignal(int contactIndex, NeoPhoneBookEntry *entry);
		void deleteContactSignal(int contactIndex);
		void callContactSignal(int contactIndex);
		void stopCallContactSignal();

    public slots: // external signal listener
		
		void disconnectionServlet();
		//===== Server (PC) =====
		int listen(QString ipStr, QString portStr);		
		int stop();
		QString getClientIp();
		QString getClientPort();
		//===== Client (Phone) =====
		void sync(QString ipStr, QString portStr);
		//===== Phone Book =====
		void addContactListener(NeoPhoneBookEntry *entry);
		void replaceContactListener(int contactIndex, NeoPhoneBookEntry *entry);
		void deleteContactListener(int contactIndex);
		void callContactListener(int contactIndex);
		void stopCallContactListener();
		

	private slots: // internal signal listener
		
		//===== Servlet (network related)
		void connectionServlet();
        void dispatcherServlet();		
		void fileUploadServlet();
		
		
		//===== Internal
		void setupServlet(int servlet);
		void messageDispatcher(QString message);	
		void setupFileUpload(QString message);
		void sendMessage(QString message);
		void errorHandler(QAbstractSocket::SocketError error);
		void sendFile(QString filename);
		void closeConnection();
		bool validateAddress(QString ipStr, QString portStr);
		void processAction(QString action);
		void sendAction(QString type, QString payload);
		int parseInt(QString);
		void emptyHome();

		//===== Phone
		void processSync();
		void processServerSync();

    private:		
        QTcpServer *server;
        QTcpSocket *client;
		QTcpSocket *socket;
	QString homeDir;
		//===== PC
		QString message;
		QString filename;
		QFile *file;
		int sizeToRead; // data size
		//===== Phone
				
};


#endif
